package com.yb.livewykt.ui.activity

import android.app.Activity
import android.content.Intent
import android.content.res.Configuration
import android.net.Uri
import android.os.Build
import android.text.TextUtils
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.LinearLayout
import androidx.activity.viewModels
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.observe
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.yb.livewykt.ui.adapter.ChatRoomMessageRecyclerAdapter
import com.yb.livewykt.ui.adapter.LiveActionRecyclerAdapter
import com.yb.livewykt.ui.model.LiveStreamPanel
import com.yb.livewykt.ui.model.PictureSelectEngine
import com.yb.livewykt.vm.LiveStreamingViewModel
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.listener.OnResultCallbackListener
import com.yb.livewykt.R
import com.yb.livewykt.bean.*
import com.yb.livewykt.databinding.ActivityLiveStreamingLayoutBinding
import com.yb.livewykt.ui.adapter.LiveBeautyRecyclerAdapter
import com.yb.livewykt.ui.adapter.LiveFilterRecyclerAdapter
import com.yb.livewykt.util.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class LiveStreamingActivity : BaseActivity(),View.OnClickListener {

    private val viewModel by viewModels<LiveStreamingViewModel>()
    private lateinit var binding: ActivityLiveStreamingLayoutBinding
    private var liveStreamPanel: LiveStreamPanel? = null
    private var actionAdapter: LiveActionRecyclerAdapter? = null
    private var isNeedUploadCover:Boolean = false
    private var coverFilePath:String = ""
    private val msgResultCode = 10022
    private var messageAdapter:ChatRoomMessageRecyclerAdapter? = null
    private val messageList:MutableList<ChatRoomTextMsg> = arrayListOf()
    private val filterAdapter:LiveFilterRecyclerAdapter = LiveFilterRecyclerAdapter(this)
    private val beautyAdapter:LiveBeautyRecyclerAdapter = LiveBeautyRecyclerAdapter(this)
    private var beauty:Beauty? = null

    override fun initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_live_streaming_layout)
        binding.data = viewModel
        binding.lifecycleOwner = this
        liveStreamPanel = LiveStreamPanel(this@LiveStreamingActivity, binding)
        liveStreamPanel?.startPreview()
        viewModel.getLastTimeData()
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        val params = window.attributes
        params.screenBrightness = 0.7f
        window.attributes = params
        val actionManager = LinearLayoutManager(this)
        actionManager.orientation = RecyclerView.VERTICAL
        binding.recyclerView.layoutManager = actionManager
        actionAdapter = LiveActionRecyclerAdapter(this, LiveAction.getAllAction())
        binding.recyclerView.adapter = actionAdapter
        val messageManager = LinearLayoutManager(this)
        messageManager.orientation =  RecyclerView.VERTICAL
        messageAdapter = ChatRoomMessageRecyclerAdapter(this, messageList)
        binding.message.layoutManager = messageManager
        binding.message.adapter = messageAdapter
        binding.actionRecycler.layoutManager = LinearLayoutManager(this).also { it.orientation = RecyclerView.HORIZONTAL }
        binding.actionRecycler.adapter = filterAdapter
    }

    override fun initListener() {
        binding.startLive.setOnClickListener(this)
        binding.cover.setOnClickListener(this)
        binding.inputPanel.setOnClickListener(this)
        viewModel.historyData.observe(this){
            if(!TextUtils.isEmpty(it.cover_img)){
                isNeedUploadCover = false
                Glide.with(this).load(it.cover_img).into(binding.cover)
                binding.title.setText(it.name)
                binding.title.setSelection(it.name.length)
                binding.editTitle.text = resources.getString(R.string.edit)
                viewModel.canEditTitle.value = false
            }else{
                isNeedUploadCover = true
            }
        }

        viewModel.startLiveRTMP.observe(this){
            Glide.with(this).load(it.cover_img).into(binding.cover)
            binding.title.setText(it.name)
            binding.title.setSelection(it.name.length)
            liveStreamPanel?.setPushUrl(it.pushUrl)
            liveStreamPanel?.startLive()
            viewModel.isObserverMessage(true)
            viewModel.getChatRoomHistoryMessage()
            binding.constraintLayout.transitionToEnd()
            viewModel.isLiving.value = true
            binding.editTitle.text = resources.getString(R.string.edit)
            viewModel.canEditTitle.value = false
        }

        viewModel.showErrorMsg.observe(this){
            it.msg.showToast()
        }
        binding.editTitle.setOnClickListener(this)
        liveStreamPanel?.networkDisconnect?.observe(this){
            if (it){
                liveStreamPanel?.stopLive()
                binding.constraintLayout.transitionToStart()
                viewModel.isLiving.value = false
            }
        }
        viewModel.chatRoomMessagesLiveData.observe(this){
            Log.d(TAG, "initListener: $it")
            messageList.add(it)
            messageAdapter?.notifyDataSetChanged()
        }
        actionAdapter?.setOnItemClickListener {
            Log.d(TAG, "initListener: $it")
            when(it){
                LiveAction.switchCamera ->{
                    liveStreamPanel?.switchCamera()
                }
                LiveAction.filter ->{
                    val filterDialog = AlertDialogUtil.showFilterDialog(this)
                    filterDialog.show()
                    val param = filterDialog.window?.attributes
                    param?.width = getScreenWidth()
                    param?.gravity = Gravity.BOTTOM
                    param?.windowAnimations = R.style.dialog_enter_exit
                    filterDialog.window?.attributes = param
                }
                LiveAction.beauty ->{
                    val beautyDialog = AlertDialogUtil.showBeautyDialog(this)
                    beautyDialog.show()
                    val param = beautyDialog.window?.attributes
                    param?.width = getScreenWidth()
                    param?.gravity = Gravity.BOTTOM
                    param?.windowAnimations = R.style.dialog_enter_exit
                    beautyDialog.window?.attributes = param
                }
                LiveAction.share ->{
                    resources.getString(R.string.write_something).showToast()
                }
                LiveAction.shop ->{
                    resources.getString(R.string.write_something).showToast()
                }
            }
        }

        AlertDialogUtil.seekBarValue.observe(this){
            liveStreamPanel?.setFilterLevel(it.toFloat())
        }
        AlertDialogUtil.beautySeekBar.observe(this){
            liveStreamPanel?.setBeautyLevel(beauty,it.toFloat())
        }
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        liveStreamPanel?.onConfigurationChanged()
        super.onConfigurationChanged(newConfig)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK){
            viewModel.sendTextMessage(data?.getStringExtra(CHAT_ROOM_INPUT_CONNECT).toString())
        }
    }

    override fun onBackPressed() {
        if (viewModel.isLiving.value!!){
            return
        }
        liveStreamPanel?.stopLive()
        viewModel.isObserverMessage(false)
        binding.constraintLayout.transitionToStart()
        viewModel.isLiving.value = false
        super.onBackPressed()
    }


    override fun onClick(p0: View?) {
        when(p0?.id){

            R.id.cover -> {
                PictureSelector
                    .create(this)
                    .openGallery(PictureMimeType.ofImage())
                    .selectionMode(PictureConfig.SINGLE)
                    .isGif(false)
                    .isEnableCrop(true)
                    .enableCrop(true)
                    .withAspectRatio(1, 1)
                    .cropImageWideHigh(400, 400)
                    .freeStyleCropEnabled(true)
                    .scaleEnabled(true)
                    .queryMaxFileSize(10f)
                    .isReturnEmpty(true)
                    .imageEngine(PictureSelectEngine())
                    .forResult(object : OnResultCallbackListener<LocalMedia> {
                        override fun onResult(result: MutableList<LocalMedia>?) {
                            Glide.with(this@LiveStreamingActivity).load(result?.get(0)!!.path).into(
                                binding.cover)
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                                isNeedUploadCover = true
                                coverFilePath = uriToFileQ(this@LiveStreamingActivity, Uri.parse(
                                    result?.get(
                                        0)!!.path))!!.absolutePath
                            } else {
                                isNeedUploadCover = true
                                coverFilePath = result?.get(0).path
                            }
                        }

                        override fun onCancel() {

                        }

                    })
            }
            R.id.edit_title -> {
                if (viewModel.canEditTitle.value!!) {
                    viewModel.canEditTitle.value = false
                    binding.editTitle.text = resources.getString(R.string.edit)
                    binding.title.clearFocus()
                } else {
                    if (viewModel.isLiving.value!!) {
                        resources.getString(R.string.living_not_edit).showToast()
                        return
                    }
                    viewModel.canEditTitle.value = true
                    binding.editTitle.text = resources.getString(R.string.sure)
                    binding.title.requestFocus()
                }
            }
            R.id.input_panel -> {
                val intent = Intent(this, LiveBottomInputPanelActivity::class.java)
                startActivityForResult(intent, msgResultCode)
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun getMessageEvent(messageEvent: MessageEvent){
        if (messageEvent.messageEventEnum == MessageEventEnum.FILTER){
            val filter = messageEvent.any as Filter
            liveStreamPanel?.setFilterName(filter)
        }else if (messageEvent.messageEventEnum == MessageEventEnum.BEAUTY){
            beauty = messageEvent.any as Beauty
        }
    }
}